<?php

namespace app\cms\service;

use app\cms\model\cmsWareInboundDetail;
use app\cms\model\CmsWareInfo;
use think\admin\model\SystemBase;
use think\admin\Service;
use think\facade\Cache;

class InboundService extends Service
{

  public function generatorCode(){
    $key = 'cms:inbound:code';
    if(Cache::has($key)){
      $rand = Cache::inc($key); 
    }else{
      Cache::set($key, 1221, 8640000);
      $rand = Cache::inc($key);
    }
   
    return 'IN-' . date('Ymd', time()) . '-' . $rand;
  }
  public function getWarehouses(): array
  {
    return CmsWareInfo::mk()->where(['deleted' => 0])->order('sort', 'asc')->select()->toArray();
  }

  public function save(array $data): bool
  {
  

    return false;
  }

  /**
   * 绑定订单详情数据
   * @param array $data
   * @param boolean $from
   * @return array
   * @throws \think\db\exception\DataNotFoundException
   * @throws \think\db\exception\DbException
   * @throws \think\db\exception\ModelNotFoundException
   */
  public function buildData(array &$data = [], bool $from = true): array
  {
    if (empty($data)) return $data;
    // 关联发货信息
    $nobs = array_unique(array_column($data, 'bill_no'));

    $cateorys = SystemBase::mk()->items('种类');
    $house = CmsWareInfo::mk()->where(['deleted' => 0])->column('ware_name', 'ware_code');

    $query = cmsWareInboundDetail::mk()->where(['deleted' => 0]);
    $items = $query->withoutField('id,deleted,created_at')->whereIn('bill_no', $nobs)->select()->toArray();
    foreach ($data as &$vo) {
      $vo['items'] = [];
      $vo['ware_user_name'] = '仓库管理员';
      $vo['product_name'] = '';
      foreach ($items as $it) if ($vo['bill_no'] === $it['bill_no']) {
        $vo['items'][] = $it;
      }
      foreach ($cateorys as $k => $ca) if ($vo['category'] === $k) {
        $vo['product_name'] = $ca['name'];
      }
      $vo['receiver_name'] = $house[$vo['receiver_code']] ?? '';
      $vo['depart_name'] = $house[$vo['depart_code']] ?? '';
    }
    return $data;
  }
}
